layui.config({
    base: "../../js/"
}).extend({
    "utilObj": "utilObj"
})
layui.use(['utilObj', 'form', 'layer', 'laydate', 'table', 'laytpl', 'laypage', 'util'], function () {
    var utilObj = layui.utilObj;//自定义模块，包含ajax
    var laypage = layui.laypage;
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;
    //用户每日登陆 和每日活跃用户数不同
    var phoneTypeUrl = "/cms/report/getMobileTypeCover";
    var phonePlatformUrl = "/cms/report/getMobilePlatformCover";
    var userActiveUrl = "/cms/report/getActiveUserByDay";
    // var userIncreaseUrl = "/cms/report/getUserIncreaseTendency";
    var userCityUrl = "/cms/report/getCityCover";
    var userPage = {
        getData: function () {
            userPage.getMobileTypeData();
            userPage.getMobilePlatformData();
            userPage.getUserActiveData();
            userPage.getUserLogin();
            userPage.getUserCity();
        },
        getUserLogin: function () {
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            utilObj.showLoading();
            utilObj.ajax({
                url: userActiveUrl,
                data: {
                    startDate: startTime,
                    endDate: endTime
                },
                success: function (data) {
                    if (data) {
                        userPage.bindUserLogin(data);
                    } else {
                        $("#userActiveList").hide();
                    }
                    utilObj.hideLoading();
                },
                error: function (err) {
                    utilObj.hideLoading();
                    $("#userActiveList").hide();
                }
            });
        },
        getUserCity: function () {
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            utilObj.showLoading();
            utilObj.ajax({
                url: userCityUrl,
                data: {
                    startDate: startTime,
                    endDate: endTime
                },
                success: function (data) {
                    if (data) {
                        if (data.length) {
                            data.sort(sortNumber);
                        }
                        userPage.bindUserCity(data);
                        userPage.renderUserCity(data);
                    } else {
                        $('#userCityList').hide()
                    }
                    utilObj.hideLoading();
                },
                error: function (err) {
                    utilObj.hideLoading();
                    $('#userCityList').hide()
                }
            });
        },
        //手机平台 android
        getMobilePlatformData: function () {
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            utilObj.showLoading();
            utilObj.ajax({
                url: phonePlatformUrl,
                data: {
                    startDate: startTime,
                    endDate: endTime
                },
                success: function (data) {
                    if (data) {
                        if (data.length) {
                            data.sort(sortNumber);
                        }
                        userPage.bindPhonePlatform(data);
                        userPage.renderPhonePlatform(data);
                    } else {
                        $('#mobilePlatformList').hide()
                    }
                    utilObj.hideLoading();
                },
                error: function (err) {
                    utilObj.hideLoading();
                    $('#mobilePlatformList').hide()
                }
            });
        },
        //手机类型
        getMobileTypeData: function () {
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            utilObj.showLoading();
            utilObj.ajax({
                url: phoneTypeUrl,
                data: {
                    startDate: startTime,
                    endDate: endTime
                },
                success: function (data) {
                    if (data) {
                        if (data.length) {
                            data.sort(sortNumber);
                        }
                        userPage.bindPhoneType(data);
                        userPage.renderMobileType(data);
                    } else {
                        $('#mobileBrandList').hide()
                    }
                    utilObj.hideLoading();
                },
                error: function () {
                    utilObj.hideLoading();
                    $('#mobileBrandList').hide()
                }
            });
        },

        getUserActiveData: function () {
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            utilObj.showLoading();
            utilObj.ajax({
                url: userActiveUrl,
                data: {
                    startDate: startTime,
                    endDate: endTime
                },
                success: function (data) {
                    if (data) {
                        userPage.bindUserActive(data);
                        userPage.renderUserActive(data);
                    } else {
                        $("#userActiveList").hide();
                        // $(".useractive-content").hide();
                    }
                    utilObj.hideLoading();
                },
                error: function () {
                    utilObj.hideLoading();
                    $("#userActiveList").hide();
                    // $('.useractive-content').hide();
                }
            });
        },

        //每日活跃用户
        bindUserActive: function (chartData) {
            //接口返回number应该为数字
            var xData = [];
            var yData = [];
            for (var index in chartData) {
                xData.push(chartData[index].date);
                yData.push(Number(chartData[index].number));
            }
            var chart = Highcharts.chart('userActive', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    type: 'line'
                },
                title: {
                    text: ''
                },
                xAxis: {
                    categories: xData
                },
                yAxis: {
                    title: {
                        text: ''
                    }
                },
                tooltip: {},
                plotOptions: {
                    line: {
                        dataLabels: {
                            enabled: true,
                            allowOverlap: true
                        },
                    }
                },
                series: [{
                    name: '用户活跃',
                    data: yData
                }]
            });
        },
        bindUserLogin: function (chartData) {
            var xData = [];
            var yData = [];
            for (var index in chartData) {
                xData.push(chartData[index].date);
                yData.push(Number(chartData[index].number));
            }
            var chart = Highcharts.chart('userLogin', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    type: 'line'
                },
                title: {
                    text: ''
                },
                xAxis: {
                    categories: xData
                },
                yAxis: {
                    title: {
                        text: ''
                    }
                },
                tooltip: {},
                plotOptions: {
                    line: {
                        dataLabels: {
                            enabled: true,
                            allowOverlap: true
                        },
                    }
                },
                series: [{
                    name: '每日用户登录数',
                    data: yData
                }]
            });
        },
        //用户登录和用户活跃数
        renderUserLogin: function (chartData) {

        },
        bindPhoneType: function (chartData) {
            var pieData = [];
            var otherCount = 0;
            for (var index in chartData) {
                if (index >= 5) {
                    otherCount += chartData[index].number;
                } else {
                    var item = {
                        name: chartData[index].platform ? chartData[index].platform : "",
                        y: chartData[index].number
                    }
                    pieData.push(item);
                }
            }
            var otherItem = {
                name: '其它',
                y: otherCount
            }
            if (pieData.length > 0) {
                pieData.push(otherItem);
            }
            console.log(pieData);
            Highcharts.chart('phoneBrand', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie'
                },
                title: {
                    text: ''
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            }
                        }
                    }
                },
                series: [{
                    name: 'Phone Type',
                    colorByPoint: true,
                    data: pieData
                }]
            });
        },
        bindPhonePlatform: function (chartData) {
            var pieData = [];
            var otherCount = 0;
            for (var index in chartData) {
                if (index >= 5) {
                    otherCount += chartData[index].number;
                } else {
                    var item = {
                        name: chartData[index].platform ? chartData[index].platform : "",
                        y: chartData[index].number
                    }
                    pieData.push(item);
                }
            }
            var otherItem = {
                name: '其它',
                y: otherCount
            };
            if (pieData.length > 0) {
                pieData.push(otherItem);
            }
            Highcharts.chart('phonePlatform', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false,
                    type: 'pie'
                },
                title: {
                    text: ''
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                            style: {
                                color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                            }
                        }
                    }
                },
                series: [{
                    name: 'Phone Type',
                    colorByPoint: true,
                    data: pieData
                }]
            });
        },
        bindUserCity: function (chartData) {
            //前十名条形图
            var lineData = [];
            for (var index in chartData) {
                if (index >= 10) {
                    break;
                }
                var items = [];
                items.push(chartData[index].city);
                items.push(chartData[index].number);
                lineData.push(items);
            }
            var chart = Highcharts.chart('userCity', {
                credits: {
                    enabled: false
                },
                legend: {
                    enabled: false
                },
                chart: {
                    type: 'column'
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    type: 'category',
                    labels: {
                        rotation: -90  // 设置轴标签旋转角度
                    }
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: '人数'
                    }
                },
                legend: {
                    enabled: false
                },
                tooltip: {
                    pointFormat: '城市分布: <b>{point.y:.0f} 人</b>'
                },
                series: [{
                    name: '城市分布',
                    data: lineData,
                    dataLabels: {
                        enabled: true,
                        rotation: -90,
                        color: '#FFFFFF',
                        align: 'right',
                        format: '{point.y:.0f}', // :.1f 为保留 1 位小数
                        y: 10
                    }
                }]
            });
        },
        renderMobileType: function (chartData) {
            if (chartData && chartData.length) {
                $(".mobilebrand-content").show();
            } else {
                $(".mobilebrand-content").hide();
            }
            table.render({
                elem: '#mobileBrandList',
                cellMinWidth: 95,
                page: true,
                height: 315,
                limit: 7,
                id: 'mobileBrandListTable',
                cols: [[
                    {
                        field: 'platform',
                        title: '手机型号',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'number',
                        title: '数量',
                        minWidth: 80,
                        align: 'center'
                    }
                ]],
                data: chartData
            });
        },
        renderPhonePlatform: function (chartData) {
            if (chartData && chartData.length) {
                $(".mobileplatform-content").show();
            } else {
                $(".mobileplatform-content").hide();
            }
            table.render({
                elem: '#mobilePlatformList',
                cellMinWidth: 95,
                page: true,
                height: 315,
                limit: 7,
                id: 'mobilePlatformListTable',
                cols: [[
                    {
                        field: 'platform',
                        title: '手机平台',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'number',
                        title: '数量',
                        minWidth: 80,
                        align: 'center'
                    }
                ]],
                data: chartData
            });

        },
        renderUserActive: function (chartData) {
            if (chartData && chartData.length) {
                $(".useractive-content").show();
            } else {
                $(".useractive-content").hide();
            }
            userPage.tableUserActive = table.render({
                elem: '#userActiveList',
                cellMinWidth: 95,
                page: true,
                height: 315,
                limit: 7,
                id: "userActiveListTable",
                cols: [[
                    {
                        field: 'date',
                        title: '日期',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'number',
                        title: '活跃用户数',
                        minWidth: 80,
                        align: 'center'
                    }
                ]],
                data: chartData
            });

        },
        renderUserCity: function (chartData) {
            if (chartData && chartData.length) {
                $(".usercity-content").show();
            } else {
                $(".usercity-content").hide();
            }
            table.render({
                elem: '#userCityList',
                cellMinWidth: 95,
                page: true,
                height: 315,
                limit: 7,
                id: 'userCityListTable',
                cols: [[
                    {
                        field: 'city',
                        title: '城市',
                        minWidth: 100,
                        align: "center"
                    },
                    {
                        field: 'number',
                        title: '用户数',
                        minWidth: 80,
                        align: 'center'
                    }
                ]],
                data: chartData
            });

        },
        checkDate: function () {
            //时间范围
            var startTime = $("#startTime").val();
            var endTime = $("#endTime").val();
            var startDate = new Date(startTime);
            var endDate = new Date(endTime);
            if (startDate.getTime() > endDate.getTime()) {
                layer.msg("开始时间不能晚于结束时间")
                return false;
            }
            var today = new Date();
            if (endTime.getTime() > today.getTime()) {
                layer.msg("结束时间不能大于今天");
                return false;
            }
            return true;
        },
        init: function () {
            Date.prototype.format = function (format) {
                var o = {
                    "M+": this.getMonth() + 1,
                    "d+": this.getDate(),
                    "h+": this.getHours(),
                    "m+": this.getMinutes(),
                    "s+": this.getSeconds(),
                    "q+": Math.floor((this.getMonth() + 3) / 3),
                    "S": this.getMilliseconds()
                }
                if (/(y+)/.test(format)) {
                    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(format)) {
                        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
                    }
                }
                return format;
            }

            Highcharts.setOptions({
                colors: ['#BDA990', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
            });
            var today = new Date();
            var endDate = today;
            var startDate = new Date();
            var year = endDate.getFullYear() - 1;
            startDate.setYear(year);

            var startStr = startDate.format("yyyy-MM-dd").toString();
            var endStr = endDate.format("yyyy-MM-dd").toString();
            //开始时间 最大值为今天
            laydate.render({
                elem: '#startTime',
                type: 'date',
                value: startStr,
                max: endStr

            });
            laydate.render({
                elem: '#endTime',
                type: 'date',
                value: endStr,
                max: endStr
            });
            userPage.getData();
        }
        ,
    };
    userPage.init();

    //对服务端返回数据进行搜索
    function sortNumber(a, b) {
        return b.number - a.number;
    }

    $(".confirm_btn").on("click", function () {
        userPage.getData(1);
    });

})